var mytable = null;
//字节大小转换，参数为b
function bytesToSize(bytes) {
    var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
    if (bytes == 0) return 'N/A';
    var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
    return (bytes / Math.pow(1024, i)).toFixed(2) + ' ' + sizes[i];
};
$(document).ready(function(){
	//元素
	var oFileBox = $(".fileBox");					//选择文件父级盒子
	var oFileInput = $("#fileInput");				//选择文件按钮
	var oFileSpan = $("#fileSpan");					//选择文件框

	var oFileList_parent = $(".fileList_parent");	//表格
	var oFileList = $(".fileList");					//表格tbody
	var fileList = [];								//数据，为一个复合数组
    $( "#uploadDiv" ).dialog({
            autoOpen: false,
            width: 800,
            modal: true,
            title: 'File Upload',
            buttons: [
                {
                    id: "fileBtn",
                    text: "Upload",
                    click: function() {
                    	doFileUpload();
                    	return false;
                    }
                },
                {
                    id: "clearBtn",
                    text: "Clear",
                    click: function() {
                        clearFileList();
                        return false;
                    }
                },
                {
                    text: "Cancel",
                    click: function() {
                        clearFileList();
                        $( this ).dialog( "close" );
                    }
                }
            ]
        });

	//拖拽外部文件，进入目标元素触发
	oFileSpan.on("dragenter",function(){
		$(this).text("可以释放鼠标了！").css("background","#ccc");
	});

	//拖拽外部文件，进入目标、离开目标之间，连续触发
	oFileSpan.on("dragover",function(){
		return false;
	});

	//拖拽外部文件，离开目标元素触发
	oFileSpan.on("dragleave",function(){
		$(this).text("Drag and drop file(s) here").css("background","none");
	});

	//拖拽外部文件，在目标元素上释放鼠标触发
	oFileSpan.on("drop",function(ev){
		var fs = ev.originalEvent.dataTransfer.files;
		analysisList(fs);		//解析列表函数
		$(this).text("Drag and drop file(s) here").css("background","none");
		return false;
	});

	//点击选择文件按钮选文件
	oFileInput.on("change",function(){
		analysisList(this.files);
	})

	//解析列表函数
	function analysisList(obj){
		//如果没有文件
		if( obj.length<1 ){
			return false;
		}

        removeOldAndInvalidItems();
		for( var i=0; i<obj.length; i++ ){
			var fileObj = obj[i];		//单个文件
			var name = fileObj.name;	//文件名
			var size = fileObj.size;	//文件大小 abc.txt + 123 = abc.txt123
			var type = fileType(name);	//文件类型，获取的是文件的后缀
			var status = 0;
			var message = "Ready to upload.";
			var flag = false;

			for( var j= 0; j<fileList.length; j++ ) {
			    var fileData = fileList[j];
			    if(name + size === fileData[1] + fileData[2]) {
			        flag = true;
			        break;
			    }
			}

			if( size > 10*1024*1024){
				message = name +' is over 10M.';
				status = 2;
			} else if(flag === true) {
			    message = name +' is existing.';
                status = 2;
			}

			//给json对象添加内容，得到选择的文件的数据
			var itemArr = [fileObj,name,size,type, status, message];	//文件，文件名，文件大小，文件类型
			fileList.push(itemArr);
		}

		createList()				//生成列表
		oFileList_parent.show();	//表格显示
		$('#fileBtn').show();
		$('#clearBtn').show();
	};

	function removeOldAndInvalidItems() {
	    for( var i=0;i<fileList.length; ){
	        var fileData = fileList[i];
			var status = fileData[4];
			if(status !== 0) {
                fileList.splice(i, 1);
                i = 0;
			} else {
			    i++;
			}
		}
	}


	//生成列表
	function createList(){
		oFileList.empty();					//先清空元素内容
		for( var i=0;i<fileList.length;i++ ){

			var fileData = fileList[i];		//fileList数组中的某一个
			var objData = fileData[0];		//文件
			var name = fileData[1];			//文件名
			var size = fileData[2];			//文件大小
			var type = fileData[3];			//文件类型
			var message = fileData[5];
			var status = fileData[4];
			var volume = bytesToSize(size);	//文件大小格式化

			var oTr = $("<tr></tr>");
			var str = '<td><cite title="'+ name +'">'+ name +'</cite></td>';
			str += '<td>'+ type +'</td>';
			str += '<td>'+ volume +'</td>';
			str += '<td><a href="javascript:;" class="operation">Delete</a></td>';
			str += '<td>';
			str += '<div class="fileLoading">';
			if(status === 2) {
			    str += "<img src='images/failed.png' width='24' height='24'/>&nbsp;&nbsp;" + message;
			} else {
			    str += message;
			}

			str += '</div>';
			str += '</td>';
			oTr.html(str);
			oTr.appendTo( oFileList );
		}
	}

	//删除表格行
	oFileList.on("click","a.operation",function(){
		var oTr = $(this).parents("tr");
		var index = oTr.index();
		oTr.remove();		//删除这一行
		fileList.splice(index,1);	//删除数据
	});

    function clearFileList() {
        oFileList.empty();
        fileList = [];
        $('#fileBtn').hide();
        $('#clearBtn').hide();
    }

	//上传
	function doFileUpload(){
		//oFileBtn.off();
		var tr = oFileList.find("tr");		//获取所有tr列表
		var cd = $('#pathHidden').val();
		var successNum = 0;					//已上传成功的数目
		//oFileList.off();					//取消删除事件
		//oFileBox.slideUp();					//隐藏输入框

		for( var i=0;i<tr.length;i++ ){
			uploadFn(tr.eq(i),i);		//参数为当前项，下标
		}

		function uploadFn(obj,i){

			var formData = new FormData();
			var arrNow = fileList[i];						//获取数据数组的当前项

			// 从当前项中获取上传文件，放到 formData对象里面，formData参数以key name的方式
			var result = arrNow[0];							//数据
			if(arrNow[4] === 2) {
			    // ignore files not match client validation.
			    return;
			}
			arrNow[4] = 1;
			formData.append("file" , result);
			formData.append("path", cd);

			var name = arrNow[1];							//文件名
			formData.append("email" , name);

			var fileLoading = obj.find(".fileLoading");			//上传进度背景元素
			var oOperation = obj.find("a.operation");		//按钮
            fileLoading.html("<img src='images/fl3.gif' width='24', height='24'/>");
			oOperation.text("Uploading...");							//改变操作按钮
			oOperation.off();

			var request = $.ajax({
				type: "POST",
				url: "/file/upload",
				data: formData,			//这里上传的数据使用了formData 对象
				processData : false, 	//必须false才会自动加上正确的Content-Type
				contentType : false,

				//这里我们先拿到jQuery产生的XMLHttpRequest对象，为其增加 progress 事件绑定，然后再返回交给ajax使用
				xhr: function(data){
				    console.log(data);
					var xhr = $.ajaxSettings.xhr();
					if(onprogress && xhr.upload) {
						xhr.upload.addEventListener("progress" , onprogress, false);　
						return xhr;
					}
				},

				//上传成功后回调
				success: function(data){
				    if(data.code == 0) {
				        oOperation.text("Success");
				        fileLoading.html("<img src='images/ok.png' width='24' height='24'/>");
				        successNum++;
				        mytable.ajax.reload();
				    } else {
				        oOperation.text("Failed");
				        fileLoading.html("<img src='images/failed.png' width='24' height='24'/>&nbsp;&nbsp;" + data.msg);
				    }
				},
				//上传失败后回调
				error: function(){
					oOperation.text("重传");
					fileLoading.html("");
					oOperation.on("click",function(){
						request.abort();		//终止本次
						uploadFn(obj,i);
					});
				}

			});

			function onprogress(evt){
			}

		}
	}
////////////////////////////
$('#uploadDivLoading').hide();
$( "#qrDiv" ).dialog({
        autoOpen: false,
        modal: true,
        title: 'QRCode',
        buttons: [
            {
                text: "Cancel",
                click: function() {
                    $( this ).dialog( "close" );
                }
            }
        ]
    });

$( "#createFolderDiv" ).dialog({
        autoOpen: false,
        width: 600,
        modal: true,
        title: 'Create Folder',
        buttons: [
            {
                text: "Create",
                click: function() {
                	var cd = $('#pathHidden').val();
                	var folderName = $('#folderName').val();
                	if(folderName === '') {
                		$('#cdmsgs').html('<span style="color:red">'+ 'Folder Name can not be empty.' + '</span>');
                		return;
                	}
                	var folderInfo = {path : cd, folderName: folderName };
                    $.ajax({
                        url: '/file/cf',
                        type: 'POST',
                        dataType: 'json',
                        data:folderInfo,
                        beforeSend : function(req) {

                        },
                         success:function(data){
                             var mymsg = data.msg || data.message;
                             var dataCode = data.code;
                             if(dataCode == '0') {
                                 $('#cdmsgs').html('<span style="color:green">'+ 'Create Folder Successfully.'+ '</span>')
                             } else {

                                 $('#cdmsgs').html('<span style="color:red">'+ 'Failed to create Folder.' + '</span>')
                             }
                             mytable.ajax.reload();

                         },
                         error:function(data){
                                alert("Fail");
                         }
                    });
                    return false;
                }
            },
            {
                text: "Cancel",
                click: function() {
                    $( this ).dialog( "close" );
                }
            }
        ]
    });

$( "#fileUpdateDiv" ).dialog({
        autoOpen: false,
        width: 800,
        resizable: true,
        modal: true,
        title: 'File Operation',
        buttons: [
            {
                text: "Delete",
                click: function() {
                	doDelete();
                }
            },
            {
            	id: "preBtn",
                text: "Previous",
                click: function() {
                    preHandler();
                }
            },
            {
            	id: 'nextBtn',
                text: "Next",
                click: function() {
                    nextHandler();
                }
            },
            {
                text: "Cancel",
                click: function() {
                	$('#preview').html('');
                    $( this ).dialog( "close" );
                }
            }
        ]
    });
$('#maskDivLoading').show();

/// myTable init
mytable = $('#table_id').DataTable(
    		{
    			dom: 'Bfrtip', //'lfrtip',//'Blfrtip', //'Bflrtip',//
    			processing: false,
    		    searchDelay: 1000,
    			paging: true,
    			serverSide: true,
    			info: true,
    			fixedHeader: true,
    			lengthMenu: [
    				[5, 10, 25, 50, 75, 100 ],
    				['5 rows', '10 rows', '25 rows', '50 rows', '75 rows', '100 rows' ],
    				],
    			lengthChange : true,
    			 select: {
    		            style:    'os'
    		        },
   		        buttons: [
   		        	'pageLength',
   		        	{
   		                text: 'Select all',
   		                action: function () {
   		                    mytable.rows().select();
   		                }
   		            },
   		            {
   		                text: 'Select none',
   		                action: function () {
   		                    mytable.rows().deselect();
   		                }
   		            },
   		            {
   		                text: 'Upload',
   		                action: function () {
   		                	$( "#uploadDiv" ).dialog("open");
   		                	var cd = $("#pathHidden").val();
                            if(cd === '') {
                                cd = 'Root';
                            }
                            $("#currentDirecoty2").html(cd)

   		                }
   		            }
   		         ,
                 {
                     text: 'Create Folder',
                     action: function () {
                    	 var cd = $("#pathHidden").val();
                    	 if(cd === '') {
                    		 cd = 'Root';
                    	 }
                    	 $("#currentDirecoty").html(cd)
                    	$('#cdmsgs').html('')
                         $( "#createFolderDiv" ).dialog("open");

                     }
                 },
                 {
                     text: 'Mobile',
                     action: function () {
                    	 $( "#qrcode" ).html('');
                    	 var path = $('#pathHidden').val();
                    	 qrHander("/fm.html?path=" + path);
                         $( "#qrDiv" ).dialog("open");

                     }
                 }
   		        ],
    			pageLength: 50,
    			//
    			fnRowCallback: function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {

                },
    			rowCallback: function( row, data ) {

    			  },
    			order: [[3, 'desc']],
    			initComplete: function( settings, json ) {
    				$('#maskDivLoading').hide();
                },
    			fnDrawCallback : function(obj){
    	           //
    	        },
    			ajax: {
    			    url: "file/list",
    			    type: "GET",
    			    dataSrc: "data",
    			    data: function (d) {
    	                var xh = $('#pathHidden').val();
    	                var qp = getQueryParam('path');
    	                if(xh == '') {
    	                	xh = qp;
    	                	var pos = qp.lastIndexOf('/');
   	                		var prePath = pos == -1 ? '' : qp.substring(pos + 1);

   	                		var pp = pos == -1 ? '' : qp.substring(0, pos);
                            var preParent = qp.indexOf('Root') == -1 ? 'Root/' + pp : pp;
                            if(pp == '') {
                            	preParent = "Root"
                            }
                            pathHandler(prePath, preParent);
    	                }
    	                console.log(xh)
    	                //指定检索参数名称，后台参数名为extraSerach
    	                d.path=xh;
    	            }

    			  },
    			  columns: [
    				  {  //行号
   					    className: "td-no",
   					    orderable: false,
   					    searchable: false,
   					     data: null,
   					     render: function (data, type, row, meta) {
    					     var no = meta.settings._iDisplayStart + meta.row + 1;
    					     console.log(meta.row);
    					     return no;
    					}
    				  },
    		            {
    		              data: "name",
    		              searchable: true,
    		              orderable: false,
    		              render: function(data, type, row, meta) {
                              if(row.size == 0) {
                            	  var result = "<a href='#' class='linkClass' onclick='pathHandler("+ '"' + data + '"' + ', "' + row.parent + '"' + ")'>" + data + "</a>";

                            	  return result;
                              }
                              var cd = $('#pathHidden').val();
                              var url = '/file/download/' + data + "?path=" + cd;
                              url = encodeURI(url);
                              var hash = url.indexOf('#');
                              if(hash != -1) {
                            	  url = url.replace(/#/g, "%23")
                                  //url = url.substring(0, hash) + '%23' + url.substring(hash + 1);
                              }
                              var qrImage = "<img height='25px' width='25px' style='cursor: pointer;padding-left:5px;border:0;vertical-align: middle;' class='linkClass' src='images/qr.png' onclick='qrHander(" + '"' + url + '"' +  ")' />";
                              var copyMsgSpanId ="copyUrlSpan" +  meta.settings._iDisplayStart + meta.row + 1;
                              var copyImage = "<img height='25px' width='25px' style='cursor: pointer;padding-left:5px;border:0;vertical-align: middle;' class='linkClass' src='images/clipboard_copy.png' onclick='urlCopyHandler(" + '"' + url + '"'  + ',"' + copyMsgSpanId + '"'+  ")' />";

                              copyImage = copyImage + "<span id='" + copyMsgSpanId+ "' style='display:none;background:#aaaaaa;color:white;border-radius:3px;z-index:1;white-space:nowrap;padding:0px 3px;'></span>";

                              var result = "<a href='" + url + "' class='linkClass'>" + data + "</a>" + qrImage + copyImage;
                              return result;
                          }
    		            },
    		            {
    		            	data: "size",
    		            	searchable: false,
    	                    orderable: true,
    	                    render: function(data, type, row, meta) {
    	                        return bytesToSize(data);
    	                    }
    		            },
    		            {
    		            	data: "modificationTime",
    		            	searchable: false,
                            orderable: true,
                            render: function (data, type, row, meta) {
                                return new Date(data).format("yyyy/MM/dd hh:mm:ss");
                           }
    		            },
    		            {
                            data: null,
                            searchable: false,
                            orderable: false,
                            render:function(data,type,row, meta){
                            	var no = meta.row + 1;
                                return "<input type='button' class='buttonClass' onclick='updateHandler("+ no +");return false;' value='Operation'/>";
                             }

                        }
    		        ]
    		}
    );

mytable
    .on( 'select', function ( e, dt, type, indexes ) {
        var rowData = mytable.rows( indexes ).data().toArray();
        // get all select rows
        var count = mytable.rows( { selected: true } ).count();
        console.log(e);
    } )
    .on( 'deselect', function ( e, dt, type, indexes ) {
        //var rowData = mytable.rows( indexes ).data().toArray();
        //console.log(JSON.stringify( rowData ));
    } )
    .on( 'user-select', function ( e, dt, type, cell, originalEvent ) {
        if ( originalEvent.target.className === 'buttonClass' || originalEvent.target.className === 'linkClass' ) {
            e.preventDefault();
        }
    } );

});

//通过文件名，返回文件的后缀名
function fileType(name){
	var nameArr = name.split(".");
	return nameArr[nameArr.length-1].toLowerCase();
}